#!/usr/bin/env python2

import os
import sys

import click


script = os.path.realpath(__file__)
root = os.path.dirname(os.path.dirname(script))
src = os.path.join(root, 'lib')

sys.path.append(src)

import hiraeth


@click.group(context_settings={'help_option_names': ['-h', '--help']})
def cli():
    """Git photo

    This is a photo manager that is integrated with git and git-annex
    """


@cli.command()
@click.argument('path-to-add')
def addpath(**kwargs):
    """
    Add path to index publishing.

    This is not a thing that is useful just yet.
    """
    path_to_add = os.path.realpath(os.path.expanduser(kwargs['path_to_add']))
    kwargs['is_index'] = False
    cfg = hiraeth.Config(root, kwargs)
    cfg.add_path(path_to_add)


@cli.group()
def publish():
    """Publish photos to the web."""
    pass


@publish.command()
@click.argument('path')
@click.argument('public')
def gallery(**kwargs):
    """Publish directory as a gallery."""
    kwargs['is_index'] = False
    app = hiraeth.App(hiraeth.Config(root, kwargs))
    sys.exit(app.main())


@publish.command()
@click.argument('path')
@click.argument('public')
def index(**kwargs):
    """Publish index of known galleries."""
    kwargs['is_index'] = True
    app = hiraeth.App(hiraeth.Config(root, kwargs))
    sys.exit(app.main(index_page=True))


@cli.group()
def thumbs():
    """Add thumbs, view thumbs."""
    pass


@thumbs.command()
@click.argument('path', nargs=-1)
@click.argument('public', nargs=1)
def add(**kwargs):
    """Generate thumbs for PATH output to PUBLIC."""
    kwargs['is_index'] = False

    # In case a wildcard is passed
    for path in kwargs['path']:
        args = kwargs
        args['path'] = path

        photo = hiraeth.Pic(path, hiraeth.Config(root, args))
        print photo.exif
        photo.make_thumbs()


@thumbs.command()
@click.argument('path', nargs=-1)
def show(**kwargs):
    """Generate thumbs for PATH output to PUBLIC."""
    kwargs['is_index'] = False

    # In case a wildcard is passed
    for path in kwargs['path']:
        args = kwargs
        args['path'] = path

        cfg = hiraeth.Config(root, args)
        photo = hiraeth.Pic(path, cfg)
        url = cfg.get('thumburl')
        fmt = ('Original:\t{original}\n'
               'Large:\t{large}\n'
               'Med:\t{medium}\n'
               'Small:\t{thumb}')
        print fmt.format(
            original=os.path.join(url, photo.thumb()['name']),
            large=os.path.join(url, photo.thumb('large')['name']),
            medium=os.path.join(url, photo.thumb('medium')['name']),
            thumb=os.path.join(url, photo.thumb('small')['name']))


@cli.command()
def setup(**kwargs):
    """
    Initialize git photo.

    Creates and adds ~/.config/git-photo/gitconfig and adds that as an
    include to an existing gitconfig.
    """
    cfg = hiraeth.Config(root, kwargs)
    cfg.setup()

if __name__ == '__main__':
    cli()
